<template>
  <div ref="wangEditor" class="g-editor"></div>
</template>

<script>
import E from 'wangeditor'
import { uploadFile } from 'common/common-models'
import { filterCosUrl } from 'filters/form'

export default {
  props: {
    value: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      editor: null
    }
  },
  watch: {
    value: {
      handler(val) {
        this.setContent(val)
      },
      immediate: true
    }
  },
  methods: {
    menuClickCallback() {
      const ele = document.getElementsByClassName('g-editor')
      for (let i = 0; i < ele.length; i++) {
        ele[i].style.zIndex = '0'
      }
      this.$refs.wangEditor.style.zIndex = '10001'
    },
    init() {
      const editor = new E(this.$refs.wangEditor);

      editor.config.menus = [
        'head',
        'bold', // 粗体
        'fontSize',
        'fontStyle',
        'italic', // 斜体
        'underline', // 下划线
        'strikeThrough',
        'indent',
        'lineHeight',
        'foreColor', // 文字颜色
        'backColor', // 背景颜色
        'link',
        'list', // 列表
        // 'todo', // 列表
        'justify', // 对齐方式
        'quote', // 引用
        'image', // 插入图片
        // 'video', // 插入视频
        'undo',
        'redo'
        // 'emoticon', // 表情
      ];
      editor.config.showFullScreen = false;
      editor.config.menuTooltipPosition = 'down'
      editor.config.height = 225
      editor.config.customUploadImg = async (files, insert) => {
        this.isLoading = true
        const params = {
          file: { raw: files[0] }
        }
        console.log(params)
        const { data } = await uploadFile(params)
        this.isLoading = false
        if (data && data.length > 0) {
          const imgUrl = data[0].filePath
          insert(filterCosUrl(imgUrl))
        }
      };
      // editor.config.customUploadVideo = async (resultFiles, insertVideoFn) => {
      //   // resultFiles 是 input 中选中的文件列表
      //   // insertVideoFn 是获取视频 url 后，插入到编辑器的方法

      //   // 上传视频，返回结果，将视频地址插入到编辑器中
      //   this.isLoading = true
      //   console.log(resultFiles[0])
      //   const res = await uploadFile(resultFiles[0])
      //   this.isLoading = false
      //   if (res && res.data) {
      //     const videoUrl = res.data
      //     insertVideoFn(filterCosUrl(videoUrl))
      //   }
      //   // insertVideoFn(videoUrl)
      // }
      editor.config.onchange = (newHtml) => {
        this.$emit('update:value', newHtml)
      };
      editor.txt.eventHooks.menuClickEvents.push(this.menuClickCallback)
      this.editor = editor;
      editor.create();
      this.setContent(this.value)
    },
    setContent(val) {
      if (this.editor) {
        if (val !== this.editor.txt.html()) {
          this.editor.txt.html(val || '');
        }
      }
    }
  },
  mounted() {
    this.init()
  }
}
</script>
